#!/usr/bin/python
# -*- coding: utf-8 -*-
import tornado.web as torweb
import web_const as w_const
import datetime
from bson.objectid import ObjectId

# pylint: disable=R0904
# pylint: disable=W0142

class XTrackHandler(torweb.RequestHandler):
    def __init__(self, application, request, **kwargs):
        torweb.RequestHandler.__init__(self, application, request, **kwargs)
        db = w_const.DATABASE_CONNECTION.xtrack
        self._intervention_coll = db.intervention
        
    def get(self):
        action = self.get_argument('action', default='', strip=True)
        if not action:
            kk = w_const.CONFIGURATION["string_list"]
            self.render('master.html', **kk)
            return
        
        if action in w_const.template_dico.keys():
            if action in w_const.template_default_dico.keys():
                kk = w_const.template_default_dico[action]
                self.render(w_const.template_dico[action], **kk)
                return
            else:
                self.render(w_const.template_dico[action])
                return
        else:
            # show default internal web page
            self.render(w_const.template_dico['error_page'])

    def post(self):
        form_id = self.get_argument(w_const.FORM_ID_KEY, "", True)
        try:
            if form_id in ["add_intervention_form"]:
                self._post_add_intervention_form_handler()
                return
            if form_id in ["search_intervention_form"]:
                self._post_search_intervention_form_handler()
                return
            
        except: # pylint: disable=W0702
            # send error page
            self.render(w_const.template_dico['result_page'], **{"result": "KO"})
            return
        
        self.render(w_const.template_dico['error_page'])
        
    def _post_add_intervention_form_handler(self):
        operator = self.get_argument('operator', default="", strip=True)
        requestor = self.get_argument('requestor', default="", strip=True)
        time = self.get_argument('time' , default="", strip=True)
        subject = self.get_argument('subject', default="", strip=True)
        full_description = self.get_argument('full_description', default="", strip=True)
        impacted_kits = self.get_arguments('impacted_kits', strip=True)
        operator_comments = self.get_argument('operator_comments', default="", strip=True)
        date = datetime.datetime.utcnow()
        #ajout de l'entrée dans la base
        r = {'operator': operator, 'requestor': requestor, 'time': time, 'date': date, 'subject': subject, 'full_description': full_description, 'impacted_kits': impacted_kits, 'operator_comments': operator_comments}
        self._intervention_coll.insert(r)                
        self.render(w_const.template_dico['result_page'], **{"result": "OK"})
        
        
    def _post_search_intervention_form_handler(self):
        operator = self.get_argument('operator', default="", strip=True)
        requestor = self.get_argument('requestor', default="", strip=True)
        subject = self.get_argument('subject', default="", strip=True)
        full_description = self.get_argument('full_description', default="", strip=True)
        impacted_kits = self.get_arguments('impacted_kits', strip=True)
        operator_comments = self.get_argument('operator_comments', default="", strip=True)
        
        request = {}
        # create the request
        if operator:
            request['operator'] = {'$regex': operator, '$options': 'i'}
        if requestor:
            request['requestor'] = {'$regex': requestor, '$options': 'i'}
        if subject:
            request['subject'] = {'$regex': subject, '$options': 'i'}
        if full_description:
            request['full_description'] = {'$regex': full_description, '$options': 'i'}
        if operator_comments:
            request['operator_comments'] = {'$regex': operator_comments, '$options': 'i'}
    
        # TODO: ajouter ici le critère sur le kit
        
        interventions = self._intervention_coll.find(request)
        result_list = []
        for intervention in interventions:
            intervention['date'] = intervention['date'].strftime("%Y-%m-%d %H:%M")
            result_list.append(intervention)
        self.render(w_const.template_dico['result_search_page'], **{"result_list": result_list})



class ViewInter(torweb.RequestHandler):
    def __init__(self, application, request, **kwargs):
        torweb.RequestHandler.__init__(self, application, request, **kwargs)
        db = w_const.DATABASE_CONNECTION.xtrack
        self._intervention_coll = db.intervention
        
    def get(self):
        id = self.get_argument('id', default='', strip=True)
        intervention = None
        if id:
            request = {"_id": ObjectId(id)}
            intervention = self._intervention_coll.find_one(request)
            
            
            
        self.render(w_const.template_dico['vue_intervention'], **{"intervention": intervention})